/* eslint-disable no-nested-ternary */
import * as api from './api';
import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess,
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
export const GET_INIT_DATA_BEGIN = 'GET_INIT_DATA_BEGIN';
export const GET_INIT_DATA_SUCCESS = 'GET_INIT_DATA_SUCCESS';
export const GET_INIT_DATA_FAIL = 'GET_INIT_DATA_FAIL';
import moment from 'moment';
import {isYesNo} from '../Enum';
import {conventTableCondition} from '../utils';

/*==============================初始化或清理数据================================= */
//清除数据
export const CLEAR_DATA = 'CLEAR_DATA';
export const clearData = () => ({
    type: CLEAR_DATA
});

const getInitDataBegin = () => ({
    type: GET_INIT_DATA_BEGIN
});

const getInitDataSuccess = data => ({
    type: GET_INIT_DATA_SUCCESS,
    data
});

const getInitDataFail = () => ({
    type: GET_INIT_DATA_FAIL
});

/*==============================初始化API================================= */
//获取初始化数据和权限
export const getInitData = () => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.getInitData().then(res => {
        if(res.ok)
            dispatch(getInitDataSuccess(res.data));
        else
            dispatch(getInitDataFail());
        return res.ok;
    });
    const permissions = getCurrentUserPagePermissionsApi(PAGE_CODE).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return Promise.all([init, permissions]).then(values => values[0] && values[1]);
};

/*==============================查询列表================================= */
export const GET_LIST_DATA_BEGIN = 'GET_LIST_DATA_BEGIN';
export const GET_LIST_DATA_SUCCESS = 'GET_LIST_DATA_SUCCESS';
export const GET_LIST_DATA_FAIL = 'GET_LIST_DATA_FAIL';
const getListDataBegin = () => ({
    type: GET_LIST_DATA_BEGIN
});

const getListDataSuccess = (condition, data) => ({
    type: GET_LIST_DATA_SUCCESS,
    condition,
    data
});

const getListDataFail = () => ({
    type: GET_LIST_DATA_FAIL
});

/*==============================技术升级截止时间区间处理================================= */
const technologyActivityDate = (condition = {}) => {
    const {technologyActivityDate, ...others} = condition;
    if(!technologyActivityDate || technologyActivityDate.length === 0) return condition;
    return {
        ...others,
        startTime: moment(technologyActivityDate[0]).toISOString(),
        endTime: moment(technologyActivityDate[1]).toISOString(),
    };
};
/*=============================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN,
});

export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data,
});

const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});

//获取详情
export const getDetail = id => dispatch => {
    dispatch(getDetailBegin());
    return api.getDetail(id).then(res => {
        if(res.ok)
            dispatch(getDetailSuccess({
                ...res.data.details
            }));
        else
            dispatch(getDetailFail());
    });
};

//获取查询列表
export const getList = condition => dispatch => {
    dispatch(getListDataBegin());
    const queryCondition = technologyActivityDate(condition);
    let isDealerApply = undefined;
    if(condition.isDealerApply === isYesNo.是)
        isDealerApply = true;
    if(condition.isDealerApply === isYesNo.否)
        isDealerApply = false;
    return api.getList({
        ...queryCondition,
        isDealerApply
    }).then(res => {
        if(res.ok)
            dispatch(getListDataSuccess(condition, res.data));
        else
            dispatch(getListDataFail());
    });
};
//修改查询条件
export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});

//重置查询条件
export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});

//选择查询条件
export const SAVE_QUERY_DEALER = 'SAVE_QUERY_DEALER';
export const saveQueryDealer = data => ({
    type: SAVE_QUERY_DEALER,
    data
});

/*=============================提交================================== */
export const onClickSubmit = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.submitData(id, {rowVersion});
};

/*=============================作废================================== */
export const onClickAbandon = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.abandonData(id, {rowVersion});
};

/*=============================发布================================== */
export const onClickPublish = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.publishData(id, {rowVersion});
};

/*=============================关闭================================== */
export const onClickClose = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.closeData(id, {rowVersion});
};

// 审核通过 审核不通过 驳回
export const approveOrder = condition => {
    const {id, approvedResult, rowVersion, approveComment} = condition;
    if(condition.approvedResult === 1)
        return api.passData(id, {
            approvedResult,
            rowVersion,
            approveComment
        });
    else if(condition.approvedResult === 2)
        return api.rejectToPrevData(id, {
            approvedResult,
            rowVersion,
            approveComment
        });
    return api.rejectData(id, {
        approvedResult,
        rowVersion,
        approveComment
    });
};

/*==============================导出================================= */
export const exportData = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryCondition']).toJS();
    const queryCondition = technologyActivityDate(conventTableCondition(condition));
    let isDealerApply = undefined;
    if(queryCondition.isDealerApply === isYesNo.是)
        isDealerApply = true;
    if(queryCondition.isDealerApply === isYesNo.否)
        isDealerApply = false;
    return api.exports({
        ...queryCondition,
        isDealerApply});
};

//按钮搜索
export const querySearch = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryCondition']).toJS();
    dispatch(getList(condition));
};
//分页排序搜索
export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

export const onSubmit = (data, dealerId) => () => {
    const condition = {
        dealerId,
        remark: data.remark,
        endVIN: data.endVIN,
        brandId: data.brandId,
        content: data.content,
        endTime: data.endTime,
        details: data.details,
        beginVIN: data.beginVIN,
        startTime: data.startTime,
        checkLabor: data.checkLabor,
        supplierId: data.supplierId,
        dutyUnitId: data.dutyUnitId,
        serviceName: data.serviceName,
        attachments: data.attachments,
        wholesaleDealerId: data.dealerId,
        endRolloutDate: data.endRolloutDate,
        isClaimPart: data.isClaimPart === 1,
        vehicleCategory: data.vehicleCategory,
        checkChangeLabor: data.checkChangeLabor,
        isClaimAssist: data.isClaimAssist === 1,
        beginRolloutDate: data.beginRolloutDate,
        productCategoryId: data.productCategoryId,
        checkChangeAssistLabor: data.checkChangeAssistLabor,
        technologyActivityMaterial: data.technologyActivityMaterial,
    };
    return data.id ? api.updateOrder(data.id, {
        ...condition,
        rowVersion: data.rowVersion
    }).then(res => ({success: res.ok}))
        : api.newOrder(condition).then(res => ({success: res.ok}));
};
